package com.example.demo.controller;

import com.example.demo.constant.Constants;
import com.example.demo.mapper.UserInfoMapper;
import com.example.demo.model.Result;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import com.example.demo.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @PostMapping("/login")
    public Result login(@RequestParam String userName, @RequestParam String password) {
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            log.info("账号密码为空 userName {}, password {}", userName, password);
            return Result.fail("账号或者密码为空");
        }
        UserInfo userInfo = userInfoService.selectByName(userName);
        if (userInfo == null) {
            return Result.fail("用户不存在");
        }
        if (!password.equals(userInfo.getPassword())) {
            return Result.fail("账号或者密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", userInfo.getId());
        map.put("userName", userInfo.getUserName()); // 修正了这里的键名
        String jwtToken = JWTUtils.getJwtToken(map);
        return Result.success(jwtToken);
    }
   /*
    获取当前登录用户的信息
    */
    @RequestMapping("/getUserInfo")
    public UserInfo getLoginUserInfo(HttpServletRequest request){
        log.info("获取用户信息....");
        //获取token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        //从token中获取登录用户ID
        Integer userId = JWTUtils.getIdByToken(token);
        if (userId==null){
            //用户未登录
            return null;
        }
        UserInfo userInfo = userInfoService.selectById(userId);
        return userInfo;
    }

    /**
     * 根据博客ID, 获取作者信息
     * @param blogId
     * @return
     */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){

        if (blogId<=0){
            return null;
        }
        UserInfo userInfo = userInfoService.getAuthorInfo(blogId);
        return userInfo;
    }
}
